#!/bin/bash
# nc_perf_test.sh

HOST="localhost"
PORT="8888"
DURATION=30
CONCURRENT=50

echo "开始性能测试: $CONCURRENT 并发，持续 $DURATION 秒"

# 启动多个后台进程
start_time=$(date +%s)
end_time=$((start_time + DURATION))

count=0
success=0
fail=0

while [ $(date +%s) -lt $end_time ]; do
    for i in $(seq 1 $CONCURRENT); do
        (
            if echo "test $(date +%s%N)" | nc -w 2 $HOST $PORT > /dev/null 2>&1; then
                echo "success" >> /tmp/nc_result.$$
            else
                echo "fail" >> /tmp/nc_result.$$
            fi
        ) &
        count=$((count + 1))
    done
    sleep 0.1
done

wait

# 统计结果
success=$(grep -c "success" /tmp/nc_result.$$ 2>/dev/null || echo 0)
fail=$(grep -c "fail" /tmp/nc_result.$$ 2>/dev/null || echo 0)
rm -f /tmp/nc_result.$$

echo "测试完成"
echo "总请求数: $count"
echo "成功: $success"
echo "失败: $fail"
echo "成功率: $(echo "scale=2; $success * 100 / $count" | bc)%"
echo "QPS: $(echo "scale=2; $success / $DURATION" | bc)"
